import { PageContainer, ProList } from "@ant-design/pro-components";
import { Button, message, Popconfirm, Tag } from "antd";
import OrganizationStyle from "./style";
import { useGetOrganizations_service } from "../../service/organization";
import Edit from "./cpms/edit";
import { useCallback, useState } from "react";
import { useMutation } from "@apollo/client";
import { delOrganization } from "../../graphql/organization";
import { CURRENT_ORG } from "../../constant";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { setCurrentOrg } from "../../store/org";
import { RootState } from "../../store";
import Classnames from "classnames";

const Organization = () => {
  const [fetch_delOrganization_service] = useMutation(delOrganization);
  const [pageCount, setPageCount] = useState(1);
  const { data, loading, refetch, page } = useGetOrganizations_service(
    pageCount,
    10
  );
  const [editOpen, setEditOpen] = useState(false);
  const [spickOrg, setSpicOrg] = useState<Record<string, any>>({});
  const [orgId, setOrgId] = useState(undefined);
  const dispatch = useDispatch();
  const OrgEditClick = () => {
    setEditOpen(true);
    setOrgId(spickOrg.id);
  };
  const { org } = useSelector(
    (state: RootState) => ({
      org: state.orgReducer.currentOrg,
    }),
    shallowEqual
  );
  const setOpenState = useCallback((value: boolean) => {
    // setOrgId(undefined);
    setEditOpen(value);
  }, []);
  const refechOrgs = useCallback(() => {
    void refetch();
  }, []);
  const itemMouseEnter = (item: Record<string, any>) => {
    setSpicOrg(item);
  };
  const addOrganizationClick = () => {
    setEditOpen(true);
    setOrgId(undefined);
  };

  const delBtnComfirm = () => {
    void fetch_delOrganization_service({
      variables: {
        id: spickOrg.id as string,
      },
    }).then(() => {
      void message.success("删除成功");
      void refetch();
    });
  };

  const pageListClick = (page: number) => {
    setPageCount(page);
  };

  const choossOrgClick = () => {
    const { id, name } = spickOrg as { id: string; name: string };
    localStorage.setItem(
      CURRENT_ORG,
      JSON.stringify({
        id,
        name,
      })
    );
    dispatch(setCurrentOrg({ id, name }));
    void message.success("切换门店成功");
  };
  const dataSource = data?.map((item) => ({
    ...item,
    subTitle: (
      <div key={item.id}>
        {(item?.tags as string)?.split("，").map((tag) => (
          <Tag color="#5BD8A6" key={tag}>
            {tag}
          </Tag>
        ))}
      </div>
    ),
    actions: [
      <li key="run" onClick={() => OrgEditClick()} className="editBtn">
        编辑
      </li>,
      <Popconfirm
        title="删除门店"
        description="你确认删除该门店吗?"
        onConfirm={delBtnComfirm}
        okText="确认"
        cancelText="取消"
      >
        <li className="delBtn">删除</li>
      </Popconfirm>,
      <Button
        className={Classnames("choossOrg", {
          activeOrg: org.id === item.id,
        })}
        onClick={choossOrgClick}
      >
        {org.id === item.id ? "当前选中门店" : "选择该门店"}
      </Button>,
    ],
  }));
  return (
    <OrganizationStyle>
      <PageContainer
        loading={loading}
        extra={
          <Button key="1" type="primary" onClick={() => addOrganizationClick()}>
            新增门店
          </Button>
        }
      >
        <ProList
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: false,
            total: page?.total,
            onChange: pageListClick,
            current: pageCount,
          }}
          grid={{ gutter: 10, column: 2 }}
          onItem={(record: any) => {
            return {
              onMouseEnter: () => {
                itemMouseEnter(record);
              },
            };
          }}
          metas={{
            title: {
              dataIndex: "name",
            },
            subTitle: {},
            type: {},
            avatar: {
              dataIndex: "logo",
            },
            content: {
              dataIndex: "address",
            },
            actions: {
              cardActionProps: "extra",
            },
          }}
          dataSource={dataSource}
        />
        {editOpen && (
          <Edit
            open={editOpen}
            setOpenState={setOpenState}
            id={orgId}
            refechOrgs={refechOrgs}
          />
        )}
      </PageContainer>
    </OrganizationStyle>
  );
};

export default Organization;
